/**
 * 
 */
package com.google.code.jkippt.http.paging;

import java.util.Iterator;

/**
 * Iterator over paged result items.
 * @author Federico De Faveri defaveri@gmail.com
 */
public class PagedResultItemIterator<T> implements Iterator<T> {
	
	protected PageIterator<T> pager;
	protected Iterator<T> currentPageIterator;

	/**
	 * @param pager
	 */
	public PagedResultItemIterator(PageIterator<T> pager) {
		this.pager = pager;
	}

	/**
	 * {@inheritDoc}
	 */
	public boolean hasNext() {
		updateCurrent();
		return (currentPageIterator != null && currentPageIterator.hasNext());
	}

	/**
	 * {@inheritDoc}
	 */
	public T next() {
		if (!hasNext()) throw new IllegalStateException("There are no more elements");
		return currentPageIterator.next();
	}
	
	protected void updateCurrent()
	{
		//first time
		if (currentPageIterator == null && pager.hasNext()) currentPageIterator = pager.next().iterator();
		
		if (!currentPageIterator.hasNext() && pager.hasNext()) currentPageIterator = pager.next().iterator();
	}

	/**
	 * {@inheritDoc}
	 */
	public void remove() {}

}
